package com.example.administrator.fangbook.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;


import com.example.administrator.fangbook.read.bean.Chapter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtils {
    private static final String TAG = "FileUtils";

    public static String getFilePath(String path, String fileName) {
        return (path + "/" + fileName);
    }

    public static File creatFile(String fullpath) throws IOException {
        File file = new File(fullpath);
        file.createNewFile();
        return file;
    }

    /**
     * 创造一个文件
     */
    public static File creatDirs(String dirName) {
        File dir = new File(dirName);
        if (!dir.exists() || dir.isFile()) {
            dir.mkdirs();
        }
        return dir;
    }

    public static boolean isFileExist(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }


    /*
     * if the file is exist in sd card, delete it
     */
    public static boolean deleteFile(String fullPath) {
        final File f = new File(fullPath);
        if (f.exists()) {
            deleteFileSafely(f);
            return true;
        }
        return false;
    }

    //删除文件夹内所有的数据
    public static void deleteFileDirectory(File file) {

        if (file.isFile()) {
            deleteFileSafely(file);
            return;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length == 0) {
                deleteFileSafely(file);
                return;
            }

            for (int i = 0; i < files.length; i++) {
                deleteFileDirectory(files[i]);
            }
            deleteFileSafely(file);
        }
    }


    public static boolean deletfDirectory(String path) {
        final File f = new File(path);
        if (f.exists() && f.isDirectory()) {
            File files[] = f.listFiles(); // 声明目录下所有的文件 files[];
            if (files != null) {
                for (File file : files) {  // 遍历目录下所有的文件
                    deleteFileSafely(file);
                }
            }
            deleteFileSafely(f);
            return true;
        }
        return false;
    }


    public static File writeFromBuffer(String path, String fileName, byte[] buffer) {
        File file = null;
        OutputStream output = null;
        try {
            creatDirs(path);
            String fullPath = getFilePath(path, fileName);
            if (deleteFile(fullPath)) {
                Log.d(TAG, "delete old file");
            }
            file = creatFile(fullPath);
            output = new FileOutputStream(file);
            output.write(buffer);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static File writeFromString(String fullPath, String content) {
        File file = null;
        FileWriter fw = null;
        try {
            String path = fullPath.substring(0, fullPath.lastIndexOf('/'));
            creatDirs(path);
            if (deleteFile(fullPath)) {
                Log.d(TAG, "delete old file");
            }
            file = creatFile(fullPath);
            fw = new FileWriter(file, false);
            fw.write(content);
            fw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }


    public static File writeFromString(String fullPath, String content, int i) {
        File file = null;
        FileWriter fw = null;
        try {
            String path = fullPath.substring(0, fullPath.lastIndexOf('/'));
            creatDirs(path);
            final File f = new File(fullPath);
            if (f.exists() && i == 0) {
                deleteFileSafely(f);
            }
            if (file == null) {
                file = creatFile(fullPath);
            }
            fw = new FileWriter(file, true);
            fw.write(content);
            fw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }


    static Pattern pattern0 = Pattern.compile("[\u3000]+");
    static Pattern pattern1 = Pattern.compile("[  \t]+");
    static Pattern pattern2 = Pattern.compile("[\r\n]+");
    static Pattern pattern3 = Pattern.compile("\r+");
    static Pattern pattern4 = Pattern.compile("\n+");

    /**
     * 保存章节内容
     *
     * @param bookId
     * @param chapterId
     * @param contents
     * @return
     */
    public static File saveChapterContent(String bookId, String chapterId, byte[] contents) {
        if (TextUtils.isEmpty(bookId) || TextUtils.isEmpty(chapterId) || contents == null || contents.length == 0) {
            return null;
        }
        //获取文件路径
        String path = Chapter.getSaveFilePlainTextPath(bookId, chapterId);
        //根据路径创造文件
        creatDirs(path.substring(0, path.lastIndexOf('/')));
        File file = null;
        FileWriter fw = null;
        try {
            String content = new String(contents, "utf-8");
            Matcher matcher = pattern0.matcher(content);
            if (matcher.find()) {
                content = matcher.replaceAll("");
            }
            matcher = pattern1.matcher(content);
            if (matcher.find()) {
                content = matcher.replaceAll("");
            }
            matcher = pattern2.matcher(content);
            if (matcher.find()) {
                content = matcher.replaceAll("\n");
            }
            matcher = pattern3.matcher(content);
            if (matcher.find()) {
                content = matcher.replaceAll("\n");
            }
            matcher = pattern4.matcher(content);
            if (matcher.find()) {
                content = matcher.replaceAll("\n");
            }
            if (content.endsWith("\n") || content.endsWith("\r")) {
                content = content.substring(0, content.length() - 1);
            }
            file = creatFile(path);
            fw = new FileWriter(file);
            fw.write(content);
            fw.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (file != null) {
            file.setLastModified(0);
        }
        return file;
    }

    public static void bumpChapterContent(String myBookId, String chapterId) {
        if (TextUtils.isEmpty(myBookId) || TextUtils.isEmpty(chapterId)) {
            return;
        }
        File f = new File(Chapter.getSaveFilePlainTextPath(myBookId, chapterId));
        if (f.exists() && f.isFile()) {
            long modified = f.lastModified();
            if (modified != 0) {
                InputStream is = null;
                byte[] content;
                try {
                    is = new FileInputStream(f);
                    content = new byte[is.available()];
                    is.read(content);
                } catch (FileNotFoundException e) {
                    content = null;
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                    content = null;
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (content != null) {
                    f.delete();
                    saveChapterContent(myBookId, chapterId, content);
                }
            }
        }
    }

    public static File writeFromBuffer(String fullPath, byte[] buffer) {
        File file = null;
        OutputStream output = null;
        try {
            String path = fullPath.substring(0, fullPath.lastIndexOf('/'));
            creatDirs(path);
            if (deleteFile(fullPath)) {
                Log.d(TAG, "delete old file");
            }
            file = creatFile(fullPath);
            output = new FileOutputStream(file);
            output.write(buffer);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

//    public static String readFiletoString(String fullPath, String encoding) throws ErrorMsgException {
//        byte[] data = FileUtils.readData(new File(fullPath));
//        if (data == null) {
//            throw new ErrorMsgException("数据为空");
//        }
//
//        try {
//            return new String(data, encoding);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }


    public static byte[] readData(File f) {
        if (f == null || !f.exists()) {
            return null;
        }


        int offset = 0;
        InputStream input = null;
        try {

            input = new FileInputStream(f);
            byte[] bytes = new byte[input.available()];
            int numRead = 0;
            while (offset < bytes.length && (numRead = input.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }

            return bytes;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }

    /**
     * 使用异或进行简单的密码加密
     */

//    public static String setEncrypt(String str) {
//        String sn = GlobalConstants.ENCRYPT_PASSWORD; //密钥
//        int[] snNum = new int[str.length()];
//        String result = "";
//        String temp = "";
//
//        for (int i = 0, j = 0; i < str.length(); i++, j++) {
//            if (j == sn.length())
//                j = 0;
//            snNum[i] = str.charAt(i) ^ sn.charAt(j);
//        }
//
//        for (int k = 0; k < str.length(); k++) {
//
//            if (snNum[k] < 10) {
//                temp = "00" + snNum[k];
//            } else {
//                if (snNum[k] < 100) {
//                    temp = "0" + snNum[k];
//                }
//            }
//            result += temp;
//        }
//        return result;
//    }

    /**
     * 密码解密,虽然用不到
     *
     * @return <code>String[]</code> 加密后字符串
     * @author Administrator
     * @since 1.0 2005/11/28
     */
//    public static String getEncrypt(String str) {
//        String sn = GlobalConstants.ENCRYPT_PASSWORD; //密钥
//        char[] snNum = new char[str.length() / 3];
//        String result = "";
//
//        for (int i = 0, j = 0; i < str.length() / 3; i++, j++) {
//            if (j == sn.length())
//                j = 0;
//            int n = Integer.parseInt(str.substring(i * 3, i * 3 + 3));
//            snNum[i] = (char) ((char) n ^ sn.charAt(j));
//        }
//
//        for (int k = 0; k < str.length() / 3; k++) {
//            result += snNum[k];
//        }
//        return result;
//    }

//    public static void main(String[] args) {
//        String s = "我是个傻蛋";
//        String str = setEncrypt(s);
//        System.out.println("加密后为：" + str);
//        System.out.println("解密后为：" + getEncrypt(str));
//    }
    public static String readStringFromBuffer(InputStream input) {
        int offset = 0;
        try {
            byte[] bytes = new byte[input.available()];
            int numRead = 0;
            while (offset < bytes.length && (numRead = input.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            return new String(bytes, "utf-8");

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;


    }

    static byte[] buf = new byte[1024];

    /**
     * 读json文件
     */
    public static String readAssetsJsonFile(Context context, String path) {
        String JStr;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            is = context.getAssets().open(path);
            inputStreamReader = new InputStreamReader(is, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static Bitmap readAssetsImageFile(Context context, String path) {
        InputStream is = null;
        Bitmap map = null;
        try {
            is = context.getAssets().open(path);
            map = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

    public static void copyAssetsData(Context ctx, String srcPath, String destPath, String fileName) {
        InputStream in = null;
        try {

            new File(destPath).mkdirs();

            File outFile = new File(destPath + "/" + fileName);
            in = ctx.getAssets().open(srcPath + "/" + fileName);
            if (outFile.exists()) {
                deleteFileSafely(outFile);
            }

            OutputStream out = new FileOutputStream(outFile);

            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.flush();
            in.close();
            out.close();


        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    //读取文本文件中的内容  ygzhang
    public static String readFile(File readFile) {

        String content = ""; //文件内容字符串
        try {
            InputStream instream = new FileInputStream(readFile);
            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream, "UTF-8");
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;
                //分行读取
                while ((line = buffreader.readLine()) != null) {
                    content += line + "\n";
                }
                instream.close();
            }
        } catch (FileNotFoundException e) {
            Log.d("ygzhang", "The File doesn't not exist.");
        } catch (IOException e) {
            e.getStackTrace();
        }
        return content;
    }


    public static String readAssetsData(Context ctx, String path) {
        InputStream in = null;
        try {
            in = ctx.getAssets().open(path);
            byte[] bytes = new byte[in.available()];
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            in.close();
            return new String(bytes);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * fix ibcore.io.ErrnoException: open failed: EBUSY (Device or resource busy)  文件创建失败的原因是，文件被删除后仍然被其他进程占用
     * 安全删除文件.
     *
     * @param file
     * @return ygzhang
     */
    public static boolean deleteFileSafely(File file) {
        if (file != null) {
            String tmpPath = file.getParent() + File.separator + System.currentTimeMillis();
            File tmp = new File(tmpPath);
            file.renameTo(tmp);
            return tmp.delete();
        }
        return false;
    }

    public static void renameFile(String src, String dst) {
        File srcFile = new File(src);
        if (srcFile.exists()) {
            File dstFile = new File(dst);
            if (dstFile.exists() && dstFile.isFile()) {
                dstFile.delete();
            }
            srcFile.renameTo(dstFile);
        }
    }

    public static void copyDir(String src, String dst, FileFilter filter) {
        if (TextUtils.isEmpty(src) || TextUtils.isEmpty(dst)) {
            return;
        }
        File srcDir = new File(src);
        if (srcDir.exists() && srcDir.isDirectory()) {
            File dstDir = new File(dst);
            deleteFileDirectory(dstDir);
            dstDir.mkdirs();
            File[] files = null;
            if (filter == null) {
                files = srcDir.listFiles();
            } else {
                files = srcDir.listFiles(filter);
            }
            if (files.length > 0) {
                for (File f : files) {
                    if (f.isFile()) {
                        copyFile(f.getAbsolutePath(), dst, f.getName());
                    } else if (f.isDirectory()) {
                        copyDir(f.getAbsolutePath(), dst + f.getName(), filter);
                    }
                }
            }
        }
    }

    public static boolean copyFile(String src, String dstDir, String filename) {
        boolean result = false;
        if (TextUtils.isEmpty(src) || TextUtils.isEmpty(dstDir)) {
            return result;
        }
        File srcFile = new File(src);
        if (srcFile.exists() && srcFile.isFile()) {
            if (TextUtils.isEmpty(filename)) {
                filename = srcFile.getName();
            }
            File dstFileDir = new File(dstDir);
            if (!dstFileDir.exists() && !dstFileDir.isDirectory()) {
                dstFileDir.mkdirs();
            }
            File dstFile = new File(dstDir, filename);
            if (dstFile.exists() && dstFile.isFile()) {
                dstFile.delete();
            }
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new FileInputStream(srcFile); //读入原文件
                out = new FileOutputStream(dstFile);
                byte[] buffer = new byte[1024];
                int byteread = 0;
                while ((byteread = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteread);
                }
                result = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static boolean saveBitmap2File(Bitmap bitmap, String root, String fileName) {
        boolean result = false;
        File rootFile = new File(root);
        if (!rootFile.exists() || !rootFile.isDirectory()) {
            rootFile.mkdirs();
            File nomedia = new File(rootFile, ".nomedia");
            if (!nomedia.exists() || !nomedia.isFile()) {
                try {
                    nomedia.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            nomedia = null;
        }
        File f = new File(root, fileName);
        if (f.exists()) {
            f.deleteOnExit();
        }
        FileOutputStream os = null;
        try {
            f.createNewFile();
            os = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            rootFile = null;
            f = null;
        }
        return result;
    }

    /**
     * 获取assets下的所有文件
     *
     * @param context
     * @param path
     * @return
     */
    public static List<String> readAssetsAllFile(Context context, String path) {
        List<String> list = new ArrayList<String>();
        try {
            String[] name = context.getAssets().list(path);
            for (int i = 0; i < name.length; i++) {
                list.add(name[i]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;

    }


}//end class